package com.wjr.servlet;

import com.wjr.bean.User;
import com.wjr.dao.MySqlDao;
import com.wjr.dao.UserDaoFactory;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Author: wjr
 * @Description:
 * @Date Created in  2020-08-31 23:31
 * @Modified By:
 */

public class LoginServlet extends HttpServlet {
    String encoding;
    @Override
    public void init(ServletConfig config) throws ServletException {
        //初始化字符编码
        encoding = config.getServletContext().getInitParameter("encoding");
    }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置字符编码
        req.setCharacterEncoding(encoding);

        //接收参数
        String userName = req.getParameter("userName");
        String passWord = req.getParameter("passWord");
        User user = new User(userName,passWord);
        MySqlDao dao = UserDaoFactory.get();
        if (dao.findUser(user)){
            //成功 转发向到成功页面
            req.getRequestDispatcher("/success.html").forward(req,resp);
        }else{
            //失败 提示用户输入错误
            //由后台给前台返回一段js代码
            resp.setContentType("text/html;charset=utf-8");
            PrintWriter writer = resp.getWriter();
            writer.print("<script>alert('请输入正确的账号或密码');location.href='/login.html'</script>");
        }

    }

    @Override
    public void destroy() {
        super.destroy();
    }
}
